package com.sunni.controller.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunni.controller.AjaxRes;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class FormFilter extends FormAuthenticationFilter {


    /*认证成功*/
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {

        System.out.println("认证成功");

        /*返回前台 认证成功的json数据*/

        //  0.设置输出中文
        response.setCharacterEncoding("utf-8");
        //  3.浏览器打印Json，浏览器就会自动解析Json信息。
        response.getWriter().write(
                // 2.Json转成字符串
                new ObjectMapper().writeValueAsString(
                        //  1.返回成功的Json
                        new AjaxRes(true,"登陆成功")
                )
        );

        /*响应给浏览器*/
        return false;
    }


    /*认证失败   即调用*/
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        System.out.println("认证失败");

        AjaxRes ajaxRes = new AjaxRes(false, null);

        /*e 登陆失败报的异常*/
        if (e != null){
            String errorName = e.getClass().getName();
            if (errorName.equals(UnknownAccountException.class.getName())){
                /*没有账户*/
                ajaxRes.setMsg("账号不存在");
            } else if (errorName.equals(IncorrectCredentialsException.class.getName())){
                /*密码错误*/
                ajaxRes.setMsg("密码错误");
            } else {
                /*未知异常*/
                ajaxRes.setMsg("未知异常");
            }
        }

        
        try {
            /*json 转化成 string*/
            String jsonString = new ObjectMapper().writeValueAsString(ajaxRes);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(jsonString);
        } catch (IOException e1) {
            System.out.println("e1 = " + e1);
        }

        /*响应给浏览器*/
        return false;
    }
}
